import { loginAPI, getProfileAPI } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    profile: {}
  },
  mutations: {
    // 修改token的方法
    setToken(state, payload = '') {
      state.token = payload
      if (payload) {
        setToken(payload)
      } else {
        removeToken()
      }
    },
    setProfile(state, profile) {
      state.profile = profile
    }
  },
  actions: {
    // 执行登录，拿到token 改token ==> 提交mutation
    async userLoginAction(context, { username, password }) {
      const res = await loginAPI({ username, password })
      // console.log(res.data.token)
      context.commit('setToken', res.data.token)
    },

    async getProfile(ctx) {
      const res = await getProfileAPI()
      ctx.commit('setProfile', res.data)
      return res.data.permissions
    }
  }
}
